from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import configparser,os

#获取配置文件配置
config = configparser.ConfigParser()
root_dir = os.path.dirname(os.path.abspath(__file__)) #获取当前目录
config.read(root_dir + '/config.ini')

host = config.get('mysql','host')
port = config.get('mysql','port')
user = config.get('mysql','user')
password = config.get('mysql','password')
db = config.get('mysql','db')

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://' + user + ':'+ password + '@' + host + ':'+port + '/'+db
print(SQLALCHEMY_DATABASE_URI)

#创建app
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
#跟踪对象的修改
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

#创建db
db = SQLAlchemy(app =app)

#创建表映射类
class Student(db.Model):
  __tablename__ = 'student_zs'
  id = db.Column(db.Integer,primary_key = True)
  name = db.Column(db.String(10))
  class_id = db.Column(db.Integer)
  
  def __init__(self,name,class_id):
    self.name = name
    self.class_id = class_id
    
class Class_no(db.Model):
  __tablename__ = 'class_no_zs'
  id = db.Column(db.Integer,primary_key = True)
  class_no = db.Column(db.String(10))
  
  def __init__(self,class_no):
    self.class_no = class_no
    
#创建表
db.create_all()
print('表创建成功')

#插入数据
class_no1 = Class_no('一年级')
class_no2 = Class_no('二年级')
class_no3 = Class_no('三年级')
db.session.add(class_no1)
db.session.commit()

stu1= Student('张三',1)
db.session.add(stu1)
db.session.commit()

#查询student表中的数据
result = Student.query.get(1)
#修改数据
result.name = '李四'
db.session.commit()

#查询class表中的数据
result_class = Class_no.query.get(1)
print(result_class.class_no)

#删除数据
delete_result = Class_no.query.get(1)
db.session.delete(delete_result)
db.session.commit()
